import 'package:easy_debounce/easy_debounce.dart';
import 'package:flutter_my_app/services/wallet_sdk.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
part 'wallet_provider.g.dart';

class WalletState {
  final String mnemonic;
  final String privateKey;
  final String accountAddress;
  final bool isInitialized;

  WalletState({
    required this.mnemonic,
    required this.privateKey,
    required this.accountAddress,
    required this.isInitialized,
  });
}

@riverpod
class Wallet extends _$Wallet {
  final walletSdk = WalletSDK();
  @override
  WalletState build() {
    return WalletState(
      mnemonic: '',
      privateKey: '',
      accountAddress: '',
      isInitialized: false,
    );
  }
  // 创建新钱包
  void createWallet() {
    //这里采用防抖
    EasyDebounce.debounce("createWallet", Duration(milliseconds: 1000), () async {
      final mnemonic = walletSdk.generateMnemonic();
      final privateKey = walletSdk.generateEthereumPrivateKey(mnemonic);
      final accountAddress = walletSdk.getAccountAddress(privateKey);
      //这里不要存明文。要aes加密一次
      // 保存钱包数据
      await walletSdk.saveWalletData(
        mnemonic: mnemonic,
        privateKey: privateKey,
        address: accountAddress,
      );
      state = WalletState(
        mnemonic: mnemonic,
        privateKey: privateKey,
        accountAddress: accountAddress,
        isInitialized: true,
      );
    });
  }

  // 导入钱包
  void importWallet(String mnemonic) {
    if (!walletSdk.validateMnemonic(mnemonic)) {
      throw Exception('Invalid mnemonic');
    }
    final privateKey = walletSdk.generateEthereumPrivateKey(mnemonic);
    final accountAddress = walletSdk.getAccountAddress(privateKey);
    state = WalletState(
      mnemonic: mnemonic,
      privateKey: privateKey,
      accountAddress: accountAddress,
      isInitialized: true,
    );
  }
  // 清除钱包内存数据
  void clearWallet() {
    state = WalletState(
      mnemonic: '',
      privateKey: '',
      accountAddress:'',
      isInitialized: false,
    );
  }
}
